/**
 * 角色系统核心模块
 * 处理角色管理、动作库、表情系统等
 */

// 角色基础信息接口
export interface CharacterInfo {
  id: string
  name: string
  description: string
  category: string
  tags: string[]
  author: string
  version: string
  createdAt: string
  updatedAt: string
}

// 角色资源接口
export interface CharacterAsset {
  id: string
  type: 'idle' | 'walk' | 'run' | 'jump' | 'talk' | 'emotion' | 'custom'
  name: string
  url: string
  thumbnail: string
  duration?: number
  frameCount?: number
  frameRate?: number
}

// 角色表情接口
export interface CharacterEmotion {
  id: string
  name: string
  type: 'happy' | 'sad' | 'angry' | 'surprised' | 'neutral' | 'custom'
  assets: CharacterAsset[]
  intensity: number // 0-100
}

// 角色动作接口
export interface CharacterAction {
  id: string
  name: string
  type: 'basic' | 'gesture' | 'movement' | 'interaction' | 'custom'
  assets: CharacterAsset[]
  duration: number
  loop: boolean
  transitions: {
    from: string[]
    to: string[]
    duration: number
  }
}

// 完整角色定义接口
export interface Character extends CharacterInfo {
  assets: {
    idle: CharacterAsset[]
    actions: CharacterAction[]
    emotions: CharacterEmotion[]
    custom: CharacterAsset[]
  }
  defaultPose: string
  boundingBox: {
    width: number
    height: number
    offsetX: number
    offsetY: number
  }
  metadata: {
    rigged: boolean
    animatable: boolean
    interactive: boolean
    voiceEnabled: boolean
  }
}

// 角色实例接口
export interface CharacterInstance {
  id: string
  characterId: string
  name: string
  position: { x: number; y: number }
  scale: { x: number; y: number }
  rotation: number
  opacity: number
  currentAction: string
  currentEmotion: string
  state: 'idle' | 'animating' | 'transitioning'
  properties: Record<string, any>
}

// 角色管理器类
export class CharacterManager {
  private characters = new Map<string, Character>()
  private instances = new Map<string, CharacterInstance>()
  private actionLibrary = new Map<string, CharacterAction>()
  private emotionLibrary = new Map<string, CharacterEmotion>()

  // 注册角色
  registerCharacter(character: Character) {
    this.characters.set(character.id, character)
    
    // 注册角色的动作到动作库
    character.assets.actions.forEach(action => {
      this.actionLibrary.set(`${character.id}:${action.id}`, action)
    })
    
    // 注册角色的表情到表情库
    character.assets.emotions.forEach(emotion => {
      this.emotionLibrary.set(`${character.id}:${emotion.id}`, emotion)
    })
  }

  // 获取角色
  getCharacter(characterId: string): Character | null {
    return this.characters.get(characterId) || null
  }

  // 获取所有角色
  getAllCharacters(): Character[] {
    return Array.from(this.characters.values())
  }

  // 创建角色实例
  createInstance(characterId: string, instanceId: string, options: Partial<CharacterInstance> = {}): CharacterInstance | null {
    const character = this.getCharacter(characterId)
    if (!character) return null

    const instance: CharacterInstance = {
      id: instanceId,
      characterId,
      name: options.name || character.name,
      position: options.position || { x: 0, y: 0 },
      scale: options.scale || { x: 1, y: 1 },
      rotation: options.rotation || 0,
      opacity: options.opacity || 100,
      currentAction: options.currentAction || character.defaultPose,
      currentEmotion: options.currentEmotion || 'neutral',
      state: 'idle',
      properties: options.properties || {}
    }

    this.instances.set(instanceId, instance)
    return instance
  }

  // 获取角色实例
  getInstance(instanceId: string): CharacterInstance | null {
    return this.instances.get(instanceId) || null
  }

  // 更新角色实例
  updateInstance(instanceId: string, updates: Partial<CharacterInstance>) {
    const instance = this.instances.get(instanceId)
    if (instance) {
      Object.assign(instance, updates)
    }
  }

  // 删除角色实例
  removeInstance(instanceId: string) {
    this.instances.delete(instanceId)
  }

  // 获取角色的动作列表
  getCharacterActions(characterId: string): CharacterAction[] {
    const character = this.getCharacter(characterId)
    return character ? character.assets.actions : []
  }

  // 获取角色的表情列表
  getCharacterEmotions(characterId: string): CharacterEmotion[] {
    const character = this.getCharacter(characterId)
    return character ? character.assets.emotions : []
  }

  // 播放角色动作
  playAction(instanceId: string, actionId: string): boolean {
    const instance = this.getInstance(instanceId)
    if (!instance) return false

    const character = this.getCharacter(instance.characterId)
    if (!character) return false

    const action = character.assets.actions.find(a => a.id === actionId)
    if (!action) return false

    instance.currentAction = actionId
    instance.state = 'animating'
    
    // TODO: 触发动画播放事件
    return true
  }

  // 设置角色表情
  setEmotion(instanceId: string, emotionId: string): boolean {
    const instance = this.getInstance(instanceId)
    if (!instance) return false

    const character = this.getCharacter(instance.characterId)
    if (!character) return false

    const emotion = character.assets.emotions.find(e => e.id === emotionId)
    if (!emotion) return false

    instance.currentEmotion = emotionId
    
    // TODO: 触发表情变化事件
    return true
  }

  // 搜索角色
  searchCharacters(query: string, filters: {
    category?: string
    tags?: string[]
    author?: string
  } = {}): Character[] {
    const characters = this.getAllCharacters()
    
    return characters.filter(character => {
      // 文本搜索
      const textMatch = !query || 
        character.name.toLowerCase().includes(query.toLowerCase()) ||
        character.description.toLowerCase().includes(query.toLowerCase()) ||
        character.tags.some(tag => tag.toLowerCase().includes(query.toLowerCase()))
      
      // 分类过滤
      const categoryMatch = !filters.category || character.category === filters.category
      
      // 标签过滤
      const tagsMatch = !filters.tags || 
        filters.tags.every(tag => character.tags.includes(tag))
      
      // 作者过滤
      const authorMatch = !filters.author || character.author === filters.author
      
      return textMatch && categoryMatch && tagsMatch && authorMatch
    })
  }
}

// 角色动作工具类
export class CharacterActionUtils {
  // 检查动作转换是否有效
  static canTransition(from: CharacterAction, to: CharacterAction): boolean {
    return from.transitions.to.includes(to.id) || to.transitions.from.includes(from.id)
  }

  // 计算动作转换时间
  static getTransitionDuration(from: CharacterAction, to: CharacterAction): number {
    // 优先使用目标动作的转换时间
    if (to.transitions.from.includes(from.id)) {
      return to.transitions.duration
    }
    
    // 其次使用源动作的转换时间
    if (from.transitions.to.includes(to.id)) {
      return from.transitions.duration
    }
    
    // 默认转换时间
    return 0.3
  }

  // 获取动作的关键帧
  static getActionKeyframes(action: CharacterAction, startTime: number = 0) {
    const keyframes = []
    const frameInterval = action.duration / (action.assets[0]?.frameCount || 1)
    
    for (let i = 0; i < (action.assets[0]?.frameCount || 1); i++) {
      keyframes.push({
        time: startTime + i * frameInterval,
        frame: i,
        asset: action.assets[0]
      })
    }
    
    return keyframes
  }
}

// 角色表情工具类
export class CharacterEmotionUtils {
  // 混合表情
  static blendEmotions(emotion1: CharacterEmotion, emotion2: CharacterEmotion, ratio: number): CharacterEmotion {
    return {
      id: `blend_${emotion1.id}_${emotion2.id}`,
      name: `${emotion1.name} + ${emotion2.name}`,
      type: 'custom',
      assets: [...emotion1.assets, ...emotion2.assets],
      intensity: emotion1.intensity * (1 - ratio) + emotion2.intensity * ratio
    }
  }

  // 调整表情强度
  static adjustIntensity(emotion: CharacterEmotion, intensity: number): CharacterEmotion {
    return {
      ...emotion,
      intensity: Math.max(0, Math.min(100, intensity))
    }
  }

  // 获取表情的对立表情
  static getOppositeEmotion(emotionType: CharacterEmotion['type']): CharacterEmotion['type'] {
    const opposites: Record<string, CharacterEmotion['type']> = {
      'happy': 'sad',
      'sad': 'happy',
      'angry': 'neutral',
      'surprised': 'neutral',
      'neutral': 'neutral'
    }
    
    return opposites[emotionType] || 'neutral'
  }
}

// 导出默认角色管理器实例
export const defaultCharacterManager = new CharacterManager()
